<%@ Page Language="C#" Debug="true" %>

<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.Web" %>
<script runat="server">

    private static bool showDebug = false;
    public void Page_Load()
    {
        try
        {
            if(Request["debug"] != null && Request["debug"] == "1")
            {
                showDebug = true;
            }

            // Make it easy - use Referrer
            string surveyName = String.Empty;
            string referrer = Request.UrlReferrer.ToString();
            int startPos = referrer.IndexOf("/Lists/");
            if(startPos > -1)
            {
                startPos += 7;
                surveyName = referrer.Substring(startPos, referrer.IndexOf("/", startPos));
                surveyName = surveyName.Substring(0, surveyName.IndexOf("/"));
            }
            // No Referrer then check for parameter
            if(String.IsNullOrEmpty(surveyName))
            {
                surveyName = GetParameter("Survey", true);
            }
            LogMessage(String.Concat("SurveyName: ", surveyName), true);

            // Open Site & Web
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
            using (SPSite site = SPContext.Current.Site)
	        {
	            using (SPWeb web = site.OpenWeb())
		        {
			        // Get Survey List and newest Item
                    SPList surveyList = null;
                    try
                    {
			            surveyList = web.Lists[surveyName];
                    }
                    catch(Exception ex)
                    {
                        Response.Write(String.Concat("Error in AnonymousSurveyMailer - retrieving Survey List - ", surveyName, ": ", ex.Message));
                        return;
                    }
                    //surveyList.Views["All Items"]
                    //surveyList.DefaultView
			        SPQuery surveyQuery = new SPQuery();
	        	        //surveyQuery.Query = String.Format("<Where><Eq><FieldRef Name='Survey'/><Value Type='Text'>{0}</Value></Eq></Where>", surveyName);
			        surveyQuery.Query = "<OrderBy><FieldRef Name='ID' Ascending='False' /></OrderBy>";

			        surveyQuery.RowLimit = 1;

			        SPListItemCollection surveyItems = surveyList.GetItems(surveyQuery);

                    if(surveyItems == null || surveyItems.Count == 0)
                    {
                        throw new Exception(String.Concat("No items found in list: ", surveyList));
                    }

                    SPListItem surveyItem = surveyItems[0];
                    LogMessage(String.Concat("SurveyItem retrieved:<br/>\r\n", GetFields(surveyItem, "<br/>\r\n")), true);

                    string id = GetField(surveyItem, "ID");
                    string userEmail = GetField(surveyItem, "Email");
                    if(String.IsNullOrEmpty(userEmail))
                    {
                        userEmail = GetField(surveyItem, "Email%5Fx0020%5Faddress");
                    }
                    if(String.IsNullOrEmpty(userEmail))
                    {
                        userEmail = GetField(surveyItem, "Email address");
                    }
                    if(String.IsNullOrEmpty(userEmail))
                    {
                        userEmail = GetField(surveyItem, "Emailaddress");
                    }

		            // Get Settings List
			        SPList settingsList = null;
                    try
                    {
                        settingsList = web.Lists["AnonymousSurveyMailer"];
                    }
                    catch(Exception ex)
                    {
                        Response.Write(String.Concat("Error in AnonymousSurveyMailer - retrieving Setting List: ", ex.Message));
                        return;
                    }

                    if(settingsList == null)
                    {
                        throw new Exception(String.Concat("No settings found for list: ", surveyName));
                    }

			        // Get Survey Settings
			        SPQuery query = new SPQuery();
	        	    query.Query = String.Format("<Where><Eq><FieldRef Name='Survey'/><Value Type='Text'>{0}</Value></Eq></Where>", surveyName);

	    		    SPListItemCollection settingItems = settingsList.GetItems(query);


                    string redirectUrl = string.Empty;
			        // I have the items, lets get notification settings.
        		    foreach (SPListItem item in settingItems)
        		    {
                        // Get Setting EmailTo - if none then it goes to User
				        string to = GetField(item, "EmailTo");
                        if(String.IsNullOrEmpty(to))
				        {
                            //to = userEmail;
                        }
                        // if no user email and no Setting email send it to someone:
                        if(String.IsNullOrEmpty(to))
				        {
                            to = "david@davidlwalker.com";
                        }
				        string from = GetField(item, "EmailFrom");

				        string subject = GetField(item, "Subject");
                        // Generate default Subject - very rarely used for User email
				        if(String.IsNullOrEmpty(subject))
				        {
					        subject = String.Concat("New ", surveyName, " - ID: ", id);
                            if(!String.IsNullOrEmpty(userEmail))
                            {
                                subject = String.Concat(subject, " - ", userEmail);
                            }
				        }

				        string body = GetField(item, "Body");
                        if(body.IndexOf("{AutoBody}") > -1)
                        {
                            body = string.Empty;
                        }
				        if(String.IsNullOrEmpty(body))
				        {
                            body = String.Concat("ID: ", id, "<br/>\r\n", GetFields(surveyItem, "<br/>\r\n"));
				        }
                        body = body.Replace("{ID}", GetField(surveyItem, "ID"));

                        string firstName = GetField(surveyItem, "FirstName");
                        if(String.IsNullOrEmpty(firstName))
                        {
                            firstName = GetField(surveyItem, "First Name");
                        }
                        body = body.Replace("{FirstName}", firstName);

                        LogMessage(String.Concat("SendMessage(", to, from, subject, body), true);
                        SendMessage(to, from, subject, body);

                        string url = GetField(item, "RedirectUrl");
                        url = url.Replace("{WebUrl}", web.Url);
                        if(!String.IsNullOrEmpty(url))
                        {
                            redirectUrl = url;
                        }
			        }
	
			        // Finished now Redirect
			        if(Request["Source"] != null && Request["Source"].ToString() != "")
			        {
				        Response.Redirect(Request["Source"].ToString());
			        }
			        else
			        {
                        if(String.IsNullOrEmpty(redirectUrl))
                        {
                            redirectUrl = web.Url;
                        }
				        Response.Redirect(redirectUrl);
			        }
		        }
	        }
		});
        }
        catch (Exception ex)
        {
            Response.Write(String.Concat("Error in AnonymousSurveyMailer: ", ex.Message));
        }
   }
   private static string GetParameter(string keyName)
	{
		return GetParameter(keyName, string.Empty, false);
	}

	private static string GetParameter(string keyName, bool required)
	{
		return GetParameter(keyName, string.Empty, required);
	}

	private static string GetParameter(string keyName, string defaultValue)
	{
		return GetParameter(keyName, defaultValue, false);
	}

	private static string GetParameter(string keyName, string defaultValue, bool required)
	{
		string results = string.Empty;
		if(required)
		{
			if(HttpContext.Current.Request[keyName] == null || HttpContext.Current.Request[keyName].ToString() == string.Empty)
			{
				throw new Exception(String.Concat("You must provide ", keyName, " parameter."));
			}
		}
        if(HttpContext.Current.Request[keyName] != null)
        {
			results = HttpContext.Current.Request[keyName].ToString();
        }
		return results;
	}

    public static string GetField(SPListItem item, string fieldName)
    {
        string results = string.Empty;

        try
        {
            results = item[fieldName].ToString();
        }
        catch { }

        return results;
    }

    public static string GetFieldString(SPListItem item, string fieldName)
    {
        try
        {
            string value = item.GetFormattedValue(fieldName);
            //return String.Concat(fieldName, "-", value);
            return value;
        }
        catch { }
        return null;
    }

    public static string GetFields(SPListItem item)
    {
        return GetFields(item, "\r\n");
    }

    public static string GetFields(SPListItem item, string delimiter)
    {
        string skipFields = "ID,Content Type,Modified,Created By,Modified By,Version,View Response,Type,Completed";
        System.Text.StringBuilder results = new System.Text.StringBuilder();
        try
        {
            foreach(SPField field in item.Fields)
            {
                if(!field.Hidden && !skipFields.Contains(field.Title))
                {
	                results.Append(String.Concat(field.Title, ": ", GetField(item, field.Title), delimiter));
                }
		    }
        }
        catch { }
        return results.ToString();
    }

    private static bool SendMessage(string to, string from, string subject, string body)
	{
		try
		{
			System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage();
			mailMessage.From = new System.Net.Mail.MailAddress(from);
            mailMessage.To.Add(new System.Net.Mail.MailAddress(to));
            mailMessage.Subject = subject;
		    mailMessage.Body = body;
            mailMessage.IsBodyHtml = true;
            System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();
            smtpClient.Host = "localhost";
            smtpClient.Send(mailMessage);
           	return true;
        }
        catch (Exception ex)
        {
            	LogMessage(String.Concat("Error in SendMessage: ", ex.Message));
        }
        return false;
    }

    private static void LogMessage(string message)
    {
        LogMessage(message, false);
    }

    private static void LogMessage(string message, bool debug)
    {
        if(debug && !showDebug) return;
        HttpContext.Current.Response.Write(message);
    }
</script>
